package com.yc.jpyy.commonbusiness.controller;

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSON;
import com.common.utils.manydatasource.HandlerDataSource;
import com.yc.jpyy.base.bean.RestResponse;
import com.yc.jpyy.base.controller.BaseController;
import com.yc.jpyy.commonbusiness.BaiduSDK;
import com.yc.jpyy.commonbusiness.Juhe;
import com.yc.jpyy.commonbusiness.service.CommonbusinessService;
import com.yc.jpyy.utils.Tools;

@Controller
@RequestMapping(value = "/commonbusiness")
@Scope("prototype")
public class CommonbusinessController extends BaseController {

	@Autowired
	private CommonbusinessService commonbusinessService;
	@Autowired
	private WebApplicationContext context;
	private static Logger logger = LoggerFactory
			.getLogger(CommonbusinessController.class);

	@SuppressWarnings("finally")
	@RequestMapping(value = "/getToDoList", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String getIntegritycommonbusiness(
			HttpServletRequest request) throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		request.setCharacterEncoding("UTF-8");
		try {
			String info = request.getParameter("info");
			System.out.println("info" + info);
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			List<Map<String, Object>> list = commonbusinessService.getToDoList(paramsMap);
			System.out.println(list);
			response.setReturnMsg(1, "操作成功");
			response.setListData(list);
			return response.toJSON();

		} catch (Exception e) {
			logger.error("findCompany" + e.toString());
			response.setReturnCode(1);
			response.setReturnMsg("查询失败");
			response.setReturnException(e.toString());
		} finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}
	}

	@SuppressWarnings("finally")
	@RequestMapping(value = "/getBaiduPic", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String getBaiduPic(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		request.setCharacterEncoding("UTF-8");
		try {
			String info = request.getParameter("info");
			System.out.println("info" + info);
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			BaiduSDK baidusdk = new BaiduSDK();
			String imgPath = paramsMap.get("imgpath").toString();
			String picMsg = baidusdk.getPicMsg(imgPath);
			response.setListData(picMsg);
		} catch (Exception e) {
			logger.error("findCompany" + e.toString());
			response.setReturnCode(1);
			response.setReturnMsg("查询失败");
			response.setReturnException(e.toString());
		} finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}
	}

	// 聚合短信
	@SuppressWarnings("finally")
	@RequestMapping(value = "/getJuhe", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String getJuhe(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		request.setCharacterEncoding("UTF-8");
		logger.info("-------------getJuhe-------------------");
		try {
			String info = request.getParameter("info");
			System.out.println("info" + info);
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			String mobile = paramsMap.get("mobile").toString();
			String tplid = paramsMap.get("tplid").toString();
			String tplvalue = paramsMap.get("tplvalue").toString();
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			String retValue = Juhe.getRequest2(mobile, tplid, tplvalue);
			if (retValue.equals("0")) {
				response.setReturnMsg("失败");
			}
			response.setListData(retValue);
		} catch (Exception e) {
			logger.error("findCompany" + e.toString());
			response.setReturnCode(1);
			response.setReturnMsg("查询失败");
			response.setReturnException(e.toString());
		} finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}
	}

	@SuppressWarnings("finally")
	@RequestMapping(value = "/addCalendar", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String addCalendar(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		request.setCharacterEncoding("UTF-8");
		try {
			String info = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			commonbusinessService.addCalendarService(paramsMap);
		} catch (Exception e) {
			logger.error("findCompany" + e.toString());
			response.setReturnCode(1);
			response.setReturnMsg("添加失败：" + e.toString());
			response.setReturnException(e.toString());
		} finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}
	}

	// 查询所有（查询条件并且分页）
	@SuppressWarnings("finally")
	@RequestMapping(value = "/findCalendar", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String findCalendar(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		request.setCharacterEncoding("UTF-8");
		try {
			String info = request.getParameter("info");
			System.out.println("info" + info);
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			List<Map<String, Object>> list = commonbusinessService.findCalendarService(paramsMap);
			response.setReturnMsg(1, "操作成功");
			response.setListData(list);
			return response.toJSON();

		} catch (Exception e) {
			logger.error("findBAndWDaoByParamId" + e.toString());
			response.setReturnCode(1);
			response.setReturnMsg("查询失败");
			response.setReturnException(e.toString());
		} finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}
	}

	//
	@SuppressWarnings("finally")
	@RequestMapping(value = "/updateCalendarByDatetimename", method = {
			RequestMethod.GET, RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String updateCalendarByDatetimename(
			HttpServletRequest request) throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		try {
			String info = request.getParameter("info");
			System.out.println("info" + info);
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			System.out.println("paramsMap" + paramsMap);
			String ids = paramsMap.get("arrays").toString();
			String[] arrays = ids.split(",");
			paramsMap.put("arrays", arrays);
			String dbcode = paramsMap.get("dbcode").toString();
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			int ret = commonbusinessService
					.updateCalendarByDatetimenameService(paramsMap);
			if (ret > 0) {
				response.setReturnMsg(1, "更新成功");
				return response.toJSON();
			} else {
				response.setReturnMsg(0, "更新失败");
				return response.toJSON();
			}

		} catch (Exception e) {
			logger.error("更新异常" + e.toString());
			// 异常信息
			response.setReturnCode(0);
			response.setReturnMsg("操作失败");
			response.setReturnException(e.toString());
			e.printStackTrace();
		}

		finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}

	}

	@SuppressWarnings("finally")
	@RequestMapping(value = "/deleteCalendar", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String deleteCalendar(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		try {
			String info = request.getParameter("info");
			System.out.println("info" + info);
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			System.out.println("paramsMap" + paramsMap);

			String dbcode = paramsMap.get("dbcode").toString();
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			int ret = commonbusinessService.deleteCalendarService(paramsMap);
			if (ret > 0) {
				response.setReturnMsg(1, "删除成功");
				return response.toJSON();
			} else {
				response.setReturnMsg(0, "删除失败");
				return response.toJSON();
			}

		} catch (Exception e) {
			logger.error("删除异常" + e.toString());
			// 异常信息
			response.setReturnCode(0);
			response.setReturnMsg("操作失败");
			response.setReturnException(e.toString());
			e.printStackTrace();
		}

		finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}

	}

	/**
	 * 获取二级参数信息
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/selcetCitemsInfo", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String selcetCitemsInfo(HttpServletRequest request)
			throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String, Object> resultMap = new HashMap<>();
		try {
			String info = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			resultMap = commonbusinessService.selcetCitemsInfo(paramsMap);
			resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		} catch (Exception e) {
			logger.info("selcetCitemsInfo" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "查询失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}

	}
	
	/**
	 * 根据数据源获取库名
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/getDatabasebydbcode", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String getSqlNameByDbcode(HttpServletRequest request)
			throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String, Object> resultMap = new HashMap<>();
		try {
			String info = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			//HandlerDataSource.getDataSource().toString();//A1/A101
			DruidDataSource dataSource = (DruidDataSource) context.getBean(HandlerDataSource.getDataSource().toString());
			String url = dataSource.getUrl();
			//数据库名
			String data = url.substring(url.indexOf("=")+1);
			//IP
			String ip= url.substring(url.lastIndexOf("//")+2,url.lastIndexOf(":"));
			//端口
			String port = url.substring(url.lastIndexOf(":")+1,url.lastIndexOf(";"));
			//账户
			String username = dataSource.getUsername();
			//密码
			String password = dataSource.getPassword();
			String resultStr = "Data Source=" + ip + "," + port + ";Initial Catalog=" + data + 
					           ";uid=" + username + ";password=" + password;
			//String resultStrWW = "Data Source=" + Config.getWWIP() + "," + Config.getWWPORT() + ";Initial Catalog=" + data + 
			//          ";uid=" + username + ";password=" + password;
	        resultMap.put("returnCode", 1);
			resultMap.put("ListData",resultStr);
			//resultMap.put("ListDataWW",resultStrWW);注释掉，先不用此方法
			resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		} catch (Exception e) {
			logger.info("getDatabasebydbcode" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "获取失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}

	}
	/*
	 * 获取DayCount个工作日后的日期
	 */
	
	@SuppressWarnings("finally")
	@RequestMapping(value = "/selcetCalendarByDate", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String selcetCalendarByDate(
			HttpServletRequest request) throws UnsupportedEncodingException {

		request.setCharacterEncoding("UTF-8");
		Map<String, Object> resultMap = new HashMap<>();
		try {
			String info = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			resultMap = commonbusinessService.selcetCalendarByDate(paramsMap);
			resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		} catch (Exception e) {
			logger.info("selcetCalendarByDate" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "查询失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}
	}
	
	
	/**
	 * 获取下拉机构信息
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/selcetOrganList", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String selcetOrganList(HttpServletRequest request)
			throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String, Object> resultMap = new HashMap<>();
		try {
			String info = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			resultMap = commonbusinessService.selcetOrganList(paramsMap);
			resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		} catch (Exception e) {
			logger.info("selcetCitemsInfo" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "查询失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}

	}
	
	
	/**
	 * 是否开启usbkey验证
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/getParameterContent", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String getParameterContent(HttpServletRequest request)
			throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String, Object> resultMap = new HashMap<>();
		try {
			String info = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			HandlerDataSource.setDataSource("A1");
			resultMap = commonbusinessService.getParameterContent(paramsMap);
			resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		} catch (Exception e) {
			logger.info("getParameterContent" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "查询失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}

	}
	
	
	 //获取系统时间
	@SuppressWarnings("finally")
	@RequestMapping(value = "/validateUsbkey", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String validateUsbkey(HttpServletRequest request) throws UnsupportedEncodingException {
		Map<String,Object> resultMap = new HashMap<>();
		try{
			resultMap.put("returnCode", 1);
			resultMap.put("returnMsg", "操作成功");
			resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		} catch (Exception e) {
			logger.info("validateUsbkey" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "操作失败");
		}
		finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}
		
	}
	

}
